package com.delos.rbac.intercepter;

import com.alibaba.fastjson.JSONObject;
import com.delos.rbac.context.RequestHolder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * 定义HTTP请求拦截器
 *
 * @author zouyaowen
 * @date 2020-07-27
 */
public class HttpInterceptor extends HandlerInterceptorAdapter {

    private static final String CONTENT_TYPE = "content-type";
    private static final String REQUEST_TYPE = "application/json";

    public HttpInterceptor() {
        super();
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String, Object> threadMap = new HashMap<>();
        RequestHolder.setRequestParamMap(threadMap);
        //获取请求数据
        String requestURI = request.getRequestURI();
        Enumeration<String> parameterNames = request.getParameterNames();
        JSONObject jsonParams = new JSONObject();
        while (parameterNames.hasMoreElements()) {
            String paramName = parameterNames.nextElement();
            jsonParams.put(paramName, request.getParameter(paramName));
        }
        return super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        Map<String, Object> requestParamMap = RequestHolder.getRequestParamMap();
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        RequestHolder.remove();
        // TODO 
        // 日志记录
        super.afterCompletion(request, response, handler, ex);
    }

    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        super.afterConcurrentHandlingStarted(request, response, handler);
    }
}
